<template>
  <c-sku-selector
    :spu-id="spuId"
    :show-sku.sync="showSku"
    @skuBuy="skuBuy"
  ></c-sku-selector>
</template>
<script>

import  {request} from "@xiaoe/js-tools/lib/request";
import {Toast} from "vant";
import cSkuSelector from '../c-sku-selector'
import {Sku} from "vant";

const debounce = (func, wait, immediate) => {
  let timer;

  return function () {
    //this指向debounce
    let context = this;
    //即参数，func,wait
    let args = arguments;

    //如果timer不为null, 清除定时器
    if (timer) clearTimeout(timer);

    //如果是立即执行
    if (immediate) {
      //定义callNow = !timer
      var callNow = !timer;
      //定义wait时间后把timer变为null
      //即在wait时间之后事件才会有效
      timer = setTimeout(() => {
        timer = null;
      }, wait)
      //如果callNow为true,即原本timer为null
      //那么执行func函数
      if (callNow) func.apply(context, args)
    } else {
      //如果是不立即执行
      //那就是每次重新定时
      timer = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
  }
}

export default {
  name: 'c-racks-buy',
  components:{
    cSkuSelector,
    [Sku.name]: Sku
  },
  data() {
    return {
      showSku: false,
      update_num: false,
      spuId: '',
    }
  },
  computed: {
    // 是商家店铺小程序
    inLittleProgram() {
      // 先判断是不是小程序环境
      if (window.wx && window.wx.CLIENT_ENV === "wx_miniProgram") {
        if (
          this.getQueryStrDecode("unique_type") &&
          this.getQueryStrDecode("unique_type") === "elive") {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    // 小程序环境下需要判断资质，其他环境默认为true
    littleProgramCategoryInfo() {
      if (this.inLittleProgram) {
        let needCategoryInfo = [21, 20, 7, 16, 69]; // 实物商品、电子书、打卡、圈子、组合商品需要判断资质
        if (
          needCategoryInfo.indexOf(this.goodsItem.resource_type) > -1 &&
          Array.isArray(this.categoryInfo)
        ) {
          return (
            this.categoryInfo.indexOf(Number(this.goodsItem.resource_type)) > -1
          );
        } else {
          return true;
        }
      } else {
        return true;
      }
    },
  },
  methods: {
    skuBuy(item) {
      item.sku_id = item.sku
      this.operateRating(item, item.count ? this.count + item.count : ++this.count )
    },
    buyMore: debounce(
      function (goodsItem) {
        // TODO 店铺没有资质需要拦截么？
        // 店铺小程序没资质的情况弹窗，限制购买
        // if (!this.littleProgramCategoryInfo) {
        //   Toast.clear();
        //   this.showCopyModal();
        //   return;
        // }
        this.$emit("buying", true);
        this.count = goodsItem.count
        this.update_num = goodsItem.count !== 0
        request({
          url: '/xe.spu.sku_list_for_c.list/1.0.0',
          params: {
            spu_id: goodsItem.spu_id,
          }
        }).then(res => {
          console.log('res==>',res);
          let {code, data, msg} = res;
          if (data.length && data[0].attr_value && data[0].attr_value.length >0){
            this.spuId = goodsItem.spu_id
            this.showSku = true
          }else{
            goodsItem.sku_id = data[0].sku_id
            this.operateRating(goodsItem, ++this.count)
          }
        })
      }, 1000, true),
    buyLess(goodsItem) {
      if (goodsItem.count > 0) {
        this.$emit("buying", true);
        this.operateRating(goodsItem, goodsItem.count--)
      }
    },
    operateRating(goodsItem, count) {
      let url = '/xe.transaction.user_cart.add_goods.update/1.0.0'
      request({
        url,
        params: {
          option: 'set_sku_count',
          spu_id: goodsItem.spu_id,
          sku_id: goodsItem.sku_id,
          count: count,
          update_num: this.update_num
        }
      }).then(res => {
        this.$emit("buying", false);
        let {code, data, msg} = res;
        if (code === 0) {
          this.$emit("buySuccess", count);
        } else {
          this.$emit("buyError", data);
          Toast(msg || '网络异常');
        }
      }).finally(() => {
        this.showSku = false
        this.$emit("buying", false);
      })
    },

    getQueryStrDecode: (key) => {
      let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
      let r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return decodeURI(r[2]);
      }
      return null;
    }

  }
}
</script>
